package cn.stylefeng.guns.sys.core.util;

import cn.stylefeng.guns.sys.core.properties.QiniuConfig;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.qiniu.storage.Configuration;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class QiniuUtil {

    @Resource
    private static QiniuConfig qiniuConfig;

    // 设置需要操作的账号的AK和SK
//    private static final String ACCESS_KEY = qiniuConfig.getACCESS_KEY();
    private static final String ACCESS_KEY = "77GpAdr0qbRbPaTBAoiKdKL16lnsoZsoZCDwe7Sx";
//    private static final String SECRET_KEY = qiniuConfig.getACCESS_KEY();
    private static final String SECRET_KEY = "XOmHuq-Gxhp6PzoSLFodjEsboFuu1nJJGWsTDiYL";
//    private static final String host = qiniuConfig.getHost();
    private static final String host = "https://www.file.bantianyaozg.com";
//    private static final long maxSize = qiniuConfig.getMax_size();

    // 要上传的空间
//    private static final String bucketname = qiniuConfig.getBucketname();
    private static final String bucketname = "bty-files-test";

    private static final String DOMAIN = "你的图片上传路径";


    public static String upload(byte[] bytes, String key) throws Exception {

        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Zone.autoZone());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        String accessKey = ACCESS_KEY;
        String secretKey = SECRET_KEY;
        String bucket = bucketname;
        //如果是Windows情况下，格式是 D:\\qiniu\\test.png
//        String localFilePath = "C:\\Users\\dell\\Documents\\20220225112120.jpg";
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        DefaultPutRet putRet = null;
        try {
            key = DateUtil.getStampNow() + key;
//            Response response = uploadManager.put(localFilePath, key, upToken);
            Response response = uploadManager.put(bytes, key, upToken);
            //解析上传成功的结果
            putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }
        return host + "/" + putRet.key;
    }

    public static Map<String, Object> uploadFile(MultipartFile file, String dm){
        Map<String, Object> msg = new HashMap<>(8);
        try{
            if (file.isEmpty()) {
                msg.put("code", 1);
                msg.put("msg", "上传文件不能为空");
                return msg;
            }
            byte[] bytes = file.getBytes();
            String originalFilename = file.getOriginalFilename();
            //获取文件后缀
            String pif = originalFilename.substring(originalFilename.lastIndexOf("."));
            String imageName = "";
            if(StringUtils.isBlank(dm)){
                imageName = UUID.randomUUID().toString().replaceAll("-", "") + pif;
            }else{
                imageName = dm + pif;
            }
            Map<String, Object> data = new HashMap<>(4);
            //上传到七牛云
            String url = upload(bytes, imageName);
            //0表示成功，1失败
            msg.put("code", 0);
            msg.put("msg", "上传成功");
            data.put("src", url);
            data.put("title", StringUtils.substringAfterLast(url, "/"));
            msg.put("data", data);
        }catch (Exception e){
            msg.put("code", 1);
            msg.put("msg", "上传失败");
        }
        return msg;
    }

}
